package gamewalletlogic

import (
	"context"
	"go.uber.org/zap"
	gameuserlogic "navi-mumbai/app/rpc/game/internal/logic/gameuser"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/third/game/wz"
	"net/http"
	"strconv"

	"navi-mumbai/app/rpc/game/internal/svc"
	"navi-mumbai/app/rpc/game/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserTransferToGWalletLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserTransferToGWalletLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserTransferToGWalletLogic {
	return &UserTransferToGWalletLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 转账到G端钱包
func (l *UserTransferToGWalletLogic) UserTransferToGWallet(in *pb.UserTransferToGWalletReq) (*pb.UserTransferToGWalletResp, error) {
	defer utils.RecoverPanic()

	var rsp *pb.GetOpenIdByUidResp
	var err error
	rsp, err = gameuserlogic.NewGetOpenIdByUidLogic(l.ctx, l.svcCtx).GetOpenIdByUid(&pb.GetOpenIdByUidReq{
		Uid:        in.Uid,
		ProviderId: in.ProviderId,
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	wzReq := wz.TransferToGameReq{
		User:     rsp.Nickname,
		Uid:      strconv.FormatInt(rsp.OpenId, 10),
		Amount:   in.MoneyAmount,
		TradeNo:  strconv.FormatInt(in.FlowNo, 10),
		Currency: walletkey.GetGameCurrency(in.ProviderId, in.MoneyType),
	}

	l.Logger.Infof("UserTransferToGWallet User %s uid %s Amount %s TradeNo %s Currency %s ", rsp.Nickname, wzReq.Uid,
		wzReq.Amount, wzReq.TradeNo, wzReq.Currency)
	var wzResp *wz.TransferToGameResp
	wzResp, err = wz.Hc.TransferToGame(&wzReq)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	var resp pb.UserTransferToGWalletResp
	resp.State = walletkey.UserWalletTransferToGameFlowStateFailed

	if wzResp.Code == http.StatusOK {
		resp.State = walletkey.UserWalletTransferToGameFlowStateSuccess
		resp.ExternalFlowNo = wzResp.Data.GTxId
		resp.MoneyType = walletkey.GetMoneyTypeFromGame(in.ProviderId, wzResp.Data.Currency)
		resp.NewBalance = wzResp.Data.NewBalance
		resp.OldBalance = wzResp.Data.OldBalance

		l.Logger.Infof("UserTransferToGWallet resp %#v ", resp)
	} else {
		resp.ErrMsg = strconv.FormatInt(int64(wzResp.Code), 10)
		l.Logger.Errorf("UserTransferToGWallet %#v ", wzResp)
	}

	return &resp, nil
}
